%% HY 200 - EPISTHMONIKOS YPOLOGISMOS
%% Ergasia 2
%% onomatepwnymo = Passas Virgilios
%% userID = vipassas
%% AEM = 784

clear; clc;

%%1o Meros
T = 0.0005;
m = 20000*T;
n = 2*m;
t = linspace(0,T,n+1);
p = 2*(1/2*T - t)/T;

figure(1);
plot(t,p,'b');
hold on

for i=1:m+1
    a(i)=0;
end
for i=1:m-1
    b(i)=0;
end
for i=1:n+1
    q(i)=0;
end


for j=0:m
    for i=2:n
        a(j+1)=a(j+1)+p(i)*cos((2*j*t(i)*pi)/T)+(1/n)*(p(1)+p(n+1));
    end
end
a=a*(2/n);

for j=1:m-1
    for i=2:n
        b(j)=b(j)+p(i)*sin((2*j*t(i)*pi)/T);
    end
end
b=b*(2/n);

for i=1:n+1
    for j=1:m-1
        q(i) = q(i)+a(j+1)*cos((2*j*t(i)*pi)/T)+b(j)*sin((2*j*t(i)*pi)/T)+a(m+1)*cos((2*m*t(i)*pi)/T);
    end
end

q=1/2*a(1)+q;
plot(t,q,'g');

e1=abs(p(1)-q(1));
e2=abs(p(n+1)-q(n+1));
e3=abs(p(10)-q(10));


%%2o Meros

T = 0.0005;

for m=1:100
    n=2*m;
    t = linspace(0,T,n+1);
    p = 2*(1/2*T - t)/T;
    
    for k=0:m
        a(k+1)=2*p*cos((2*k*pi*t')/T)/n;
        b(k+1)=2*p*sin((2*k*pi*t')/T)/n;
    end
   

    n1 = 200;
    t1 = linspace(0,T,n1); 
    q = 1/2*a(1)*ones(1,n1); 
    for k=1:(m-1)
        q = q +a(k+1)*cos((2*k*pi*t1)/T)+b(k+1)*sin((2*k*pi*t1)/T);
    end
    q = q + a(m+1)*cos(2*pi*m*t1/T);
    p1 = 2*(1/2*T - t1)/T;
    h=  t1(2)-t1(1);
   
    E(m)=1/2*h*(sum((p1(1:n1-1)-q(1:n1-1)).^2 + (p1(2:n1)-q(2:n1)).^2));
   
end
figure(2);
semilogy(E,'*g');


e=abs(p1(2:n1-1)-q(2:n1-1));
figure(3);
plot(t1(2:n1-1),e,'b');

